<template>
  <div class="upload-container">
    <van-uploader
      v-model="fileList"
      :after-read="handleUpload"
      :max-count="1"
      accept="image/*"
      :before-read="checkFile"
    >
      <van-button icon="plus" type="primary">上传身份证照片</van-button>
    </van-uploader>

    <!-- 识别结果展示 -->
    <div v-if="result" class="result-box">
      <van-cell title="姓名" :value="result.name || '未识别到姓名'" />
      <van-cell title="身份证号" :value="result.id_number || '未识别到身份证号'" />
    </div>

    <!-- 错误提示 -->
    <van-dialog v-model:show="showError" title="错误" :message="errorMessage" />

    <!-- 加载状态 -->
    <van-loading v-if="loading" vertical>识别中...</van-loading>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import axios from 'axios';
import { Toast } from 'vant';
// Toast.success('操作成功');

const fileList = ref([]);
const result = ref(null);
const loading = ref(false);
const showError = ref(false);
const errorMessage = ref('');

// 文件格式校验
const checkFile = (file) => {
  const isImage = file.type.startsWith('image/');
  const isLt4M = file.size / 1024 / 1024 < 4;
  if (!isImage) {
    Toast.fail('仅支持图片格式');
    return false;
  }
  if (!isLt4M) {
    Toast.fail('图片大小不能超过4MB');
    return false;
  }
  return true;
};

// 上传处理
const handleUpload = async (file) => {
  try {
    loading.value = true;
    const formData = new FormData();
    formData.append('file', file.file);

    const response = await axios.post(
      'http://127.0.0.1:8000/myapp/api/upload/',
      formData,
      { headers: { 'Content-Type': 'multipart/form-data' } }
    );

    // 打印完整响应，确认URL格式
    console.log('后端返回数据:', response.data);
    
    if (response.data.code === 200) {
      result.value = response.data.data;
      // Toast.success('识别成功');不能提示有bug
    } else {
      errorMessage.value = response.data.msg || '识别失败';
      showError.value = true;
    }
  } catch (error) {
    // 捕获并显示具体错误信息
    errorMessage.value = error.response?.data?.msg || error.message;
    showError.value = true;
  } finally {
    loading.value = false;
  }
};
</script>